5.8 練習問題1 cat コマンドを標準入力に対応させる(失敗)
5.6 cat コマンドを作る
これを改造して、コマンドライン引数でファイル名が渡されなかったら標準入力を読むようにする
code:cat.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void do_cat(const char *path);
static void die(const char *s);
code:cat.c
int
main(int argc, char *argv[])
{
int i;
if (argc < 2) {
do_cat(STDIN_FILENO);
}
for (i=1; i < argc; i++) {
do_cat(argvi);
}
exit(0);
}
コマンドライン引数にファイル名が渡されないと
argc が 1 になる
if 文の argc < 2 の条件
標準入力のマクロは STDIN_FILENO
read() の引数のファイルディスクリプタに標準入力が渡ればいい?
code:example.c
int
main(int argc, char *argv[])
{
int i;
if (argc < 2) {
do_cat(STDIN_FILENO);
}
for (i=1; i < argc; i++) {
do_cat(argvi);
}
exit(0);
}
Bad address だとよ
オウオウ、全然なんか違う感じだぞ!
「解答は本書のサポートページにて」ってあるけど、解答例が全く違うコードだぞ
https://github.com/aamine/stdlinux2-source/blob/master/cat3.c
ちょっと書き換えればイイって感じじゃないぞ
どうやら「システムコール関数」ではなくて「ストリームにかかわるライブラリ関数」を使用するパターンらしい
ということでこのまま放り出して、次の第6章へ
code:cat.c
#define BUFFER_SIZE 2048
static void
do_cat(const char *path)
{
int fd;
unsigned char bufBUFFER_SIZE;
int n;
fd = open(path, O_RDONLY);
if (fd < 0) die(path);
for (;;) {
n = read(fd, buf, sizeof buf);
if (n < 0) die(path);
if (n == 0) break;
if (write(STDOUT_FILENO, buf, n) < 0) die(path);
}
if (close(fd) < 0) die(path);
}
static void
die(const char *s)
{
perror(s);
exit(1);
}